﻿using System;
using System.IO;

namespace Builderator.Core
{
    public class LocalLoader : MarshalByRefObject
    {
        private AppDomain appDomain;
        private RemoteLoader remoteLoader;

        public string[] Assemblies
        {
            get
            {
                return this.remoteLoader.GetAssmeblies();
            }
        }

        public string[] Types
        {
            get
            {
                return this.remoteLoader.GetTypes();
            }
        }

        public LocalLoader(string pluginDirectory)
        {
            AppDomainSetup setup = new AppDomainSetup();

            setup.ApplicationName = "Plugins";

            setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;

            setup.PrivateBinPath = Path.GetDirectoryName(pluginDirectory).Substring(Path.GetDirectoryName(pluginDirectory).LastIndexOf(Path.DirectorySeparatorChar) + 1);

            setup.CachePath = Path.Combine(pluginDirectory, "cache" + Path.DirectorySeparatorChar);

            setup.ShadowCopyFiles = "true";

            setup.ShadowCopyDirectories = pluginDirectory;

            appDomain = AppDomain.CreateDomain("Plugins", null, setup);

            this.remoteLoader = (RemoteLoader)appDomain.CreateInstanceAndUnwrap("Builderator.Core", "Builderator.Core.RemoteLoader");
        }

        public void LoadAssembly(string assemblyFullName)
        {
            this.remoteLoader.LoadAssembly(assemblyFullName);
        }

        public object CreateInstance(string typeName)
        {
            return this.remoteLoader.CreateInstance(typeName);
        }
    }
}